package com.lanou.lenanapp.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;


import com.lanou.lenanapp.R;
import com.lanou.lenanapp.adapter.PopupWindowAdapter;
import com.lanou.lenanapp.db.DatabaseHelper;
import com.lanou.lenanapp.entity.greendao.IsChangeIntent;
import com.lanou.lenanapp.entity.greendao.LoginEntity;
import com.lanou.lenanapp.entity.greendao.LoginOneEntity;
import com.lanou.lenanapp.util.RegularUtil;
import com.lanou.lenanapp.view.CustomDialog;

import java.util.List;

/**
 * 账号登陆和注册页面
 */
public class LoginActivity extends Activity implements View.OnClickListener, PopupWindowAdapter.onItemClickListener {

    private Button loginBtn, nextBtn, enterBtn, visitorBtn, frogetpsw;
    private ImageView editHide, hendImage;
    private LinearLayout login, loginLinear;
    private TextView enterTitle, welcome;
    private EditText nameEdt, pswEdt, name1Edt, psw1Edt, phoneNumber;
    private DatabaseHelper helper;
    private boolean flagphone, flagname, flagpsw, flagentername, flagenterpsw;
    private int size;
    private RecyclerView popuprecyclerview;
    private GridLayoutManager manager;
    private PopupWindowAdapter adapter;
    private SharedPreferences sharedPreferences;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
    }

    private void init() {
        helper = DatabaseHelper.getHelper();
        loginBtn = (Button) findViewById(R.id.loginBtn);//注册按钮
        loginBtn.setOnClickListener(this);
        frogetpsw = (Button) findViewById(R.id.frogetpsw);//忘记密码按钮
        frogetpsw.setOnClickListener(this);
        login = (LinearLayout) findViewById(R.id.login);//登录布局
        loginLinear = (LinearLayout) findViewById(R.id.loginLinear);//注册布局
        enterTitle = (TextView) findViewById(R.id.enterTitle);//登录标题
        welcome = (TextView) findViewById(R.id.welcome);//注册标题
        nextBtn = (Button) findViewById(R.id.nextBtn);//注册的下一步按钮
        nextBtn.setOnClickListener(this);
        name1Edt = (EditText) findViewById(R.id.name1Edt);//注册 用户名的输入
        psw1Edt = (EditText) findViewById(R.id.psw1Edt);//注册 密码的输入
        phoneNumber = (EditText) findViewById(R.id.phoneNumber);//注册 手机号的输入
        enterBtn = (Button) findViewById(R.id.enterBtn);
        enterBtn.setOnClickListener(this);
        nameEdt = (EditText) findViewById(R.id.nameEdt);//登录输入昵称
        nameEdt.setOnClickListener(this);
        pswEdt = (EditText) findViewById(R.id.pswEdt);//登录输入密码
        editHide = (ImageView) findViewById(R.id.editHide);//隐藏输入密码的按钮
        editHide.setOnClickListener(this);
        visitorBtn = (Button) findViewById(R.id.visitorBtn);//游客登录
        visitorBtn.setOnClickListener(this);
        hendImage = (ImageView) findViewById(R.id.hendImage);
        hendImage.setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.visitorBtn://游客登录
                isvistor();
                break;
            case R.id.loginBtn:
                isObjectAnimator();//从登录到注册的动画
                break;
            case R.id.nextBtn://注册
                loginEntity();
                break;
            case R.id.enterBtn:
                loginEnter();//登录的账号密码判断
                break;
            case R.id.editHide://隐藏输入密码的按钮
                size++;
                if (size % 2 == 1){
                    pswEdt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }else {
                    pswEdt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                break;
            case R.id.frogetpsw://忘记密码
                Intent intent1 = new Intent(this, RetrieveActivity.class);
                startActivity(intent1);
                break;
            case R.id.hendImage:
                showPopupWindow(hendImage);
                break;
        }
    }


    /**
     * 游客登录方法
     * ***/
    private void isvistor() {
        //查找登录选择页面的表格 值是注册账号时添加的
        List<IsChangeIntent> intentList = helper.queryChange();
        if (intentList != null && intentList.size() > 0){
            //找到ischange属性
            int t = intentList.get(0).getIsChange();
            if (t == 1){//如果是1 跳转MainActivity
                helper.deleteAllLoginOne();//登录之前先清空单独数据库内容
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
            }else if (t == 0){
                helper.deleteAllLoginOne();//登录之前先清空单独数据库内容
                Intent intent = new Intent(this, ContributionActivity.class);
                startActivity(intent);
                finish();
            }
        }else if (intentList == null && intentList.size() == 0){
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 点击输入账号 弹出一个popupWindow窗口
     * **/
    private void showPopupWindow(View anchor){
        //创建一个popupwindow对象
        PopupWindow window = new PopupWindow(this);
        //通过布局加载器 将布局文件转换成一个view对象
        View contentView = getLayoutInflater().inflate(R.layout.activity_popuwindiow, null);

        popuprecyclerview = (RecyclerView) contentView.findViewById(R.id.popuprecyclerview);
        manager = new GridLayoutManager(this, 1);
        adapter = new PopupWindowAdapter();
        popuprecyclerview.setLayoutManager(manager);
        popuprecyclerview.setAdapter(adapter);
        List<LoginEntity> list = helper.queryAllLogin();//查询账号数据库
        adapter.addData(list);//添加适配器
        adapter.setonItemClick(this);

        //设置弹出窗口显示的内容
        window.setContentView(contentView);

        //设置弹出窗口的宽高
        window.setWidth(400);
        window.setHeight(300);
        //点击外部 消失
        window.setOutsideTouchable(true);
        //在nameedt下面显示
        window.showAsDropDown(hendImage);
    }

    /**
     * 输入错密码三次的弹出框
     * **/
    private void isShow() {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setMessage("密码忘记了?\n要帮您找回您的密码么?");
        builder.setTitle("温馨提示");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(LoginActivity.this, RetrieveActivity.class);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    int si;//判断输入密码错误的计数器
    /**
     * 登录信息判断
     * **/
    private void loginEnter() {
        //获得输入的手机号和密码
        String phone = nameEdt.getText().toString();
        String psw = pswEdt.getText().toString();
        //判断输入的手机号密码格式正确与否
        flagentername = RegularUtil.checkPhone(this, phone);
        flagenterpsw = RegularUtil.checkPassword(this, psw);
        //按主键(手机号)查询这一条信息(包括手机号, 昵称, 密码)
        List<LoginEntity> entity = helper.queryByIdLogin(phone);
        //如果输入格式正确进入if
        if (flagentername == true && flagenterpsw == true){
            //如果查询结果为空 则提示用户不存在
            if (entity != null && entity.size() > 0){
                //按主键(手机号)查询这一条的信息
                if (helper.isLoginSave(phone)){
                    //获得按手机号查询的密码
                    String pswright = entity.get(0).getPsw();
                    String name = entity.get(0).getName();
                    //判断密码和输入的是否一样 一样则登录成功
                    if (psw.equals(pswright)){
                        Toast.makeText(this, "恭喜...登录成功", Toast.LENGTH_SHORT).show();
                        helper.deleteAllLoginOne();//先清空单独的数据库再添加
                        // 将这一个用户的信息保存到登录数据库中
                        LoginOneEntity oneEntity = new LoginOneEntity(phone, name, psw);
                        helper.saveLoginOneList(oneEntity);
                        //查找登录选择页面的表格 值是注册账号时添加的
                        List<IsChangeIntent> intentList = helper.queryChange();
                        //找到ischange属性
                        int t = intentList.get(0).getIsChange();
                        if (t == 1){//如果是1 跳转mainactivity
                            Intent intent = new Intent(this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }else if (t == 0){
                            Intent intent = new Intent(this, ContributionActivity.class);
                            startActivity(intent);
                            finish();
                        }

                    }else {
                        //如果输入密码错误三次或三次的倍数 则弹出提示框
                        si++;
                        if (si % 3 == 0){
                            isShow();//弹出提示框
                        }
                        Toast.makeText(this, "密码输入错误", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(this, "该用户不存在...", Toast.LENGTH_SHORT).show();
                }
            }else {
                Toast.makeText(this, "该用户不存在..", Toast.LENGTH_SHORT).show();
            }
        }

    }


    /**
     * 注册信息判断
     * **/
    private void loginEntity() {
        //获得当前输入的值
        String loginname = name1Edt.getText().toString();
        String loginpsw = psw1Edt.getText().toString();
        String phone = phoneNumber.getText().toString();
        //保存到一个新的对象中
        LoginEntity entity = new LoginEntity(phone, loginname, loginpsw);
        //判断数据库中是否存在
        flagphone = RegularUtil.checkPhone(this, phone);
        flagname = RegularUtil.checkName(this, loginname);
        flagpsw = RegularUtil.checkPassword(this, loginpsw);
        if (flagname == true && flagpsw == true && flagphone == true){
            if (!helper.isLoginSave(phone) && !helper.isLoginName(loginname)){
                helper.saveLoginList(entity);//将注册信息保存到数据库中
                Toast.makeText(this, "恭喜..注册成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                helper.deleteAllLoginOne();//先清空单独的数据库
                //将本次注册的用户信息添加到单独的登录数据库中
                LoginOneEntity oneEntity = new LoginOneEntity(phone, loginname, loginpsw);
                helper.saveLoginOneList(oneEntity);
                IsChangeIntent isChangeIntent = new IsChangeIntent(null, 1);
                helper.saveChange(isChangeIntent);
                startActivity(intent);
                finish();
            }else if (helper.isLoginSave(phone)){
                Toast.makeText(this, "该手机号已经被注册了", Toast.LENGTH_SHORT).show();
            }else if (helper.isLoginName(loginname)){
                Toast.makeText(this, "该用户名已经存在", Toast.LENGTH_SHORT).show();
            }
        }
    }


    /**
     * 点击注册的动画
     * **/
    private void isObjectAnimator() {
        //布局消失和出现
        ObjectAnimator animator = new ObjectAnimator().ofFloat(login, "alpha", 1f, 0f);
        animator.setDuration(3000);
        animator.start();
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                login.setVisibility(View.GONE);
                loginLinear.setVisibility(View.VISIBLE);
            }
        });
        //登录掉下去
        ObjectAnimator animator1 = new ObjectAnimator().ofFloat(enterTitle, "translationY", 0f, 1000f);
        animator1.setDuration(6000);
        animator1.setInterpolator(new BounceInterpolator());//弹跳效果
        animator1.start();
        animator1.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                enterTitle.setVisibility(View.GONE);//播放完后给登陆隐藏
            }
        });
        //注册掉下来
        welcome.setVisibility(View.VISIBLE);
        ObjectAnimator animator2 = new ObjectAnimator().ofFloat(welcome, "translationY", 0f, 200f);
        animator2.setDuration(5000);
        animator2.setInterpolator(new BounceInterpolator());
        animator2.start();
    }


    @Override
    public void onItemOnClick(LoginEntity entity) {
        nameEdt.setText(entity.getPhone());
    }
}
